import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { In, Repository } from 'typeorm';
import { OrderGoodsEntity } from '../entity/goods';
import { UserInfoEntity } from '../../user/entity/info';
import { OrderShopEntity } from '../entity/shop';

/**
 * 订单商品服务
 */
@Provide()
export class OrderGoodsService extends BaseService {
  @InjectEntityModel(OrderGoodsEntity)
  orderGoodsEntity: Repository<OrderGoodsEntity>;

  @InjectEntityModel(UserInfoEntity)
  userInfoEntity: Repository<UserInfoEntity>;

  @InjectEntityModel(OrderShopEntity)
  orderShopEntity: Repository<OrderShopEntity>;

  @Inject()
  ctx;

  // 返回商品列表
  async appIndexList(shopId?: number, sceneId?: number) {
    const userInfo = await this.userInfoEntity.findOne({
      where: {
        id: this.ctx.user.id,
      },
    });
    if (!userInfo || !userInfo.shopId) {
      return await this.orderGoodsEntity.find({
        where: {
          id: 1,
        },
      });
    }
    const shop = await this.orderShopEntity.findOne({
      where: {
        id: userInfo.shopId,
      },
    });
    let goodId = shop.goodsId;
    if (goodId == 0) {
      goodId = 1;
    }

    if (shopId && shopId == 31) {
      goodId = 1;
    }

    if (sceneId && sceneId == 1) {
      goodId = 7;
    }

    return await this.orderGoodsEntity.find({
      where: {
        id: goodId,
      },
    });
  }

  // 根据ID返回商品详情（废弃）
  async appDetail(id: number) {
    const result = await this.orderGoodsEntity.findOne({
      where: {
        id,
      },
    });
    let switchList = null;
    if ([1, 3].includes(id)) {
      switchList = {
        1: '易洁膜',
        3: '高清膜/防蓝光膜',
      };
    } else if ([2, 4].includes(id)) {
      switchList = {
        2: '易洁膜',
        4: '高清膜/防蓝光膜',
      };
    }

    const newResult = {
      ...result,
      switchList: switchList,
    };

    return newResult;
  }

  // 根据ID返回商品详情
  async appDetailV2(id: number) {
    const result = await this.orderGoodsEntity.findOne({
      where: {
        id,
      },
    });
    let switchList = {};
    if ([2, 4, 6].includes(id)) {
      switchList = {
        2: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/classChoose/2980_yjm.png',
        4: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/classChoose/3280_flgm.png',
        6: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/classChoose/3280_gqm.png',
      };
    } else if ([1, 3, 5].includes(id)) {
      switchList = {
        1: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/classChoose/3980_yjm.png',
        3: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/classChoose/4280_flgm.png',
        5: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/classChoose/4280_gqm.png',
      }
    } else if ([7].includes(id)) {
      switchList = {
        7: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/classChoose/2680_jym.png',
      }
    }

    const newResult = {
      ...result,
      switchList: switchList,
    };

    return newResult;
  }

  // 根据ID返回商品详情
  async appDetailV3(id: number) {
    const result = await this.orderGoodsEntity.findOne({
      where: {
        id,
      },
    });
    let switchList = {};
    // if ([2, 4, 6].includes(id)) {
    //   switchList = {
    //     2: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/classChoose/2980_yjm.png',
    //     4: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/classChoose/3280_flgm.png',
    //     6: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/classChoose/3280_gqm.png',
    //   };
    // } else if ([1, 3, 5].includes(id)) {
    //   switchList = [
    //     {
    //       name: '易洁膜',
    //       code: 'CR+ETC',
    //       pic: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/yijiemo.png',
    //     },
    //     {
    //       name: '高清膜',
    //       code: 'CR+HDC',
    //       pic: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/gaoqingmo.png',
    //     },
    //     {
    //       name: '防蓝光膜',
    //       code: 'CR+BRC',
    //       pic: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/fanglanguang.png',
    //     },
    //   ]
    // } else if ([7].includes(id)) {
    //   switchList = [
    //     {
    //       name: '加硬膜',
    //       code: 'CR+ETC',
    //       pic: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/jiayingmo.png',
    //     },
    //   ]
    // }

    const newResult = {
      ...result,
      // switchList: switchList,
    };

    return newResult;
  }

  // 根据商品ID返回商品列表
  async getGoodsListById(goodsId: number) {
    return await this.orderGoodsEntity.find({
      where: {
        relatedGoodsId: goodsId,
        isDeleted: false,
      },
    });
  }

  async addGoods(body) {
    console.log(body);
    let goodsRes;

    // 判断是否存在id，如果存在则更新，否则插入
    if (body.id) {
      // 更新操作
      // 查找现有商品
      const existingGoods = await this.orderGoodsEntity.findOne({
        where: { id: body.id },
      });

      if (!existingGoods) {
        throw new Error('商品不存在');
      }

      // 更新主商品信息
      existingGoods.goodsName = body.goodsName;
      existingGoods.goodsPrice = body.goodsPrice;
      existingGoods.goodsPic = body.goodsPic;
      existingGoods.goodsDetailPic = body.goodsDetailPic;
      existingGoods.eyeType = body.eyeType;

      goodsRes = await this.orderGoodsEntity.save(existingGoods);

      // 更新关联的分类信息
      if (body.goodsCategory && Array.isArray(body.goodsCategory)) {
        // 只更新有ID的分类商品，不删除现有数据
        if (body.goodsCategory.length > 0) {
          for (const item of body.goodsCategory) {
            // 只有当item有id时才进行更新操作
            if (item.id) {
              // 查找现有的分类商品
              const existingCategory = await this.orderGoodsEntity.findOne({
                where: { id: item.id, relatedGoodsId: body.id },
              });

              // 如果找到，则更新
              if (existingCategory) {
                existingCategory.goodsName = item.goodsName || '';
                existingCategory.goodsPrice = item.goodsPrice || 0;
                existingCategory.goodsPic = item.goodsPic || null;
                existingCategory.goodsDetailPic = item.goodsDetailPic || null;
                existingCategory.eyeType = item.eyeType || null;
                existingCategory.goodsDescription =
                  item.goodsDescription || null;

                await this.orderGoodsEntity.save(existingCategory);
              }
            } else {
              // 当item.id为空时，执行插入操作
              const newCategory = new OrderGoodsEntity();
              newCategory.goodsName = item.goodsName || '';
              newCategory.goodsPrice = item.goodsPrice || 0;
              newCategory.goodsPic = item.goodsPic || null;
              newCategory.goodsDetailPic = item.goodsDetailPic || null;
              newCategory.goodsDescription = item.goodsDescription || null;
              newCategory.eyeType = item.eyeType || null;
              newCategory.relatedGoodsId = body.id;

              await this.orderGoodsEntity.save(newCategory);
            }
          }
        }
      }
    } else {
      // 插入操作（原有逻辑）
      const goods = new OrderGoodsEntity();
      goods.goodsName = body.goodsName;
      goods.goodsPrice = body.goodsPrice;
      goods.goodsPic = body.goodsPic;
      goods.goodsDetailPic = body.goodsDetailPic;
      goods.eyeType = body.eyeType;
      goodsRes = await this.orderGoodsEntity.save(goods);

      // 处理goodsCategory数组，设置relatedGoodsId并批量保存
      if (
        body.goodsCategory &&
        Array.isArray(body.goodsCategory) &&
        body.goodsCategory.length > 0
      ) {
        const categoryEntities = body.goodsCategory.map(item => {
          const categoryEntity = new OrderGoodsEntity();
          categoryEntity.goodsName = item.goodsName || '';
          categoryEntity.goodsPrice = item.goodsPrice || 0;
          categoryEntity.goodsPic = item.goodsPic || null;
          categoryEntity.goodsDetailPic = item.goodsDetailPic || null;
          categoryEntity.goodsDescription = item.goodsDescription || null;
          categoryEntity.eyeType = item.eyeType || null;
          categoryEntity.relatedGoodsId = goodsRes.id;
          return categoryEntity;
        });

        await this.orderGoodsEntity.save(categoryEntities);
      }
    }

    return goodsRes;
  }

  async page(query) {
    let res;
    const goods = this.orderGoodsEntity
      .createQueryBuilder('goods')
      .where('goods.relatedGoodsId IS NULL')
      .andWhere('goods.isDeleted = false');

    // 关键词搜索 (keyWordLikeFields: ['a.goodsName'])
    if (query.keyWord) {
      goods.andWhere('goods.goodsName LIKE :keyWord', {
        keyWord: `%${query.keyWord}%`,
      });
    }

    // 等值查询 (fieldEq: ['a.orderId'])
    if (query.orderId) {
      goods.andWhere('goods.orderId = :orderId', { orderId: query.orderId });
    }
    goods.orderBy(query.order, (query.sort || '').toUpperCase());
    res = {
      list: await goods
        .skip((query.page - 1) * query.size)
        .take(query.size)
        .getMany(),
      pagination: {
        page: query.page,
        size: query.size,
        total: await goods.getCount(),
      },
    };

    return res;
  }

  // 根据ID返回商品详情
  async getGoodsDetail(body) {
    const gooods = await this.orderGoodsEntity.findOne({
      where: {
        id: body.id,
        isDeleted: false,
      },
    });
    const goodsCategory = await this.orderGoodsEntity.find({
      where: {
        relatedGoodsId: body.id,
        isDeleted: false,
      },
    });
    return {
      ...gooods,
      goodsCategory,
    };
  }

  // 重写delete方法 逻辑删除
  async delete(ids: any): Promise<void> {
    console.log(ids);
    // 如果ids是单个id，转换为数组
    const idArray = Array.isArray(ids) ? ids : [ids];

    // 遍历所有id，执行逻辑删除
    for (const id of idArray) {
      const goods = await this.orderGoodsEntity.find({
        where: {
          id,
        },
      });
      let goodsList = goods.map(item => {
        item.isDeleted = true;
        return item;
      });
      await this.orderGoodsEntity.save(goodsList);
    }
  }

  // 根据商品ID列表获取商品金额
  async getGoodsMoneyByIds(body: { goodsIds: number[] }) {
    const goods = await this.orderGoodsEntity.find({
      where: {
        id: In(body.goodsIds),
        isDeleted: false,
      },
    });
    const resData = goods.reduce((acc, item) => {
      acc[item.id] = {
        id: item.id,
        goodsPrice: item.goodsPrice,
      };
      return acc;
    }, {});
    return resData;
  }

  // 根据商品ID获取商品的配镜限制
  async getGoodsLensDataByIds(body: { goodsIds: number }) {
    console.log(body.goodsIds);
    const goods = await this.orderGoodsEntity.findOne({
      where: {
        id: body.goodsIds,
        isDeleted: false,
      },
    });
    return goods;
  }
}
